from tornado.web import RequestHandler

from common.json import j, jj
import json
from importlib import import_module
from common.db import DB

def JsonResponse(hander, code, msg=None, data=None):
    response = {}
    response['code'] = code
    response['msg'] = msg
    response['data'] = data

    hander.write(response)


class _Root(RequestHandler):

    @property
    def db(self):
        if not self._db:
            app = import_module(self.__module__.split('.')[0])
            conf = import_module('config')
            connection = conf.DATABASES[app.database][conf.TEST]
            self._db = DB(**connection).session
        return self._db

    def prepare(self):
        self._db = None        
        self.set_header('Access-Control-Allow-Origin', '*')
        self.__prepare_get_and_post_parameters()

    def on_finish(self):
        if self._db:
            self._db.close()

    def options(self):
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE')
        self.set_header('Access-Control-Max-Age', 86400)
        self.set_header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
        self.write('')

    def __prepare_get_and_post_parameters(self):
        POST, GET = {}, {}
        if self.request.headers.get('Content-Type', '').find('application/json') >= 0:
            body = self.request.body
            if body:
                POST = json.loads(body.decode())
        else:
            for k, v in self.request.body_arguments.items():
                POST[k] = v[-1].decode()

        for k, v in self.request.query_arguments.items():
            GET[k] = v[-1].decode()

        self.POST = POST
        self.GET = GET
        self.GETPOST = jj(GET, POST)
